<?php
namespace Api\Service\Amazon;
use Home\Service\CommonService;

class ReportSaleService extends CommonService{
    protected $reportReceiptsModel = NULL;
    protected $fbaInboundShipmentPlanDetailModel = NULL;
    protected $prepareneedsService = NULL;
    public $count = 0;
    public $page = 0;
    public function __construct(){
        $this->reportSaleModel = D('Amazon\ReportSale');
        $this->reportInventoryModel = D('Amazon\ReportInventory');
        $this->reportUnsuppressedInventoryModel = D('Amazon\ReportUnsuppressedInventory');
        $this->fbaInboundShipmentPlanDetailModel = D('Inbound/Inboundshipmentplandetail', 'Model');
        $this->prepareneedsService = D('Inbound/Prepareneeds', 'Service');
    }

    public function selectData($options){
        $reportSaleData = $this->reportSaleModel->fbaSaleData($options);
        $reportInventorySaleData = $this->getInventoryData($reportSaleData, $options);

        return (!empty($reportInventorySaleData)) ? $reportInventorySaleData : false;
    }

    public function downloadData($options){
        $reportSaleData = $this->reportSaleModel->selectData($options);
        $reportInventorySaleData = $this->getInventoryData($reportSaleData);

        $downloadData = $reportInventorySaleData['reportDataLists'];
        $this->export($downloadData,"FBA库存销量报表(FBA备货参数)_".date('Y-m-d',time()));

    }

    /**
     * 参数：$reportData
     * 返回：array
     * 作者：橙子
     */
    public function getInventoryData($reportSaleData, $options) {
        $accountIds = array();
        $sellerManName = array();

        if (!empty($reportSaleData)) {
            foreach ($reportSaleData as $data) {
                $accountIds[] = $data['account_id'];
            }
        }

        $inventoryData = $this->reportInventoryModel->getInventoryBySellerSku($options);
        $unsuppressedInventoryData =
            $this->reportUnsuppressedInventoryModel->getUnsuppressedInventoryBySellerSku($options);
        var_dump($unsuppressedInventoryData);exit;
        $oceanShippingData = $this->fbaInboundShipmentPlanDetailModel->getOceanShipping($options);
        $airTransportData = $this->fbaInboundShipmentPlanDetailModel->getAirTransport($options);
        $saleConfirmQuantityData = $this->fbaInboundShipmentPlanDetailModel->getSaleConfirmQuantity($options);


        if (!empty($inventoryData)) {
            foreach ($inventoryData as $value) {
                $accountIds[] = $value['account_id'];
            }
        }

        if (!empty($unsuppressedInventoryData)) {
            foreach ($unsuppressedInventoryData as $value) {
                $accountIds[] = $value['account_id'];
            }
        }

        if (!empty($oceanShippingData)) {
            foreach ($oceanShippingData as $value) {
                $accountIds[] = $value['account_id'];
            }
        }

        if (!empty($airTransportData)) {
            foreach ($airTransportData as $value) {
                $accountIds[] = $value['account_id'];
            }
        }

        if (!empty($saleConfirmQuantity)) {
            foreach ($saleConfirmQuantity as $value) {
                $accountIds[] = $value['account_id'];
            }
        }

        $sellerManData = M('fba_account_sellers', ' ', 'fbawarehouse')
            ->where(array('account_id' => array('IN', array_unique($accountIds)), 'is_used' => 1))
            ->getField('account_id,seller_ids');

        $saleStatusData = M('statusdics', ' ', 'fbawarehouse')
            ->where(array('table' => 'api_account_seller_sku'))
            ->getField('number,value');

        foreach ($sellerManData as $accountId => $sellerMan) {
            $sellerIds = array_filter(explode(',' ,$sellerMan));
            if (!empty($sellerIds)) {
                $sellerName = M('ea_admin', ' ', 'amazonadmin')
                    ->where(array('id' => array('IN', $sellerIds)))->getField('remark', TRUE);
                $sellerManName[$accountId] = implode(',', $sellerName);
            } else {
                $sellerManName[$accountId] = '';
            }
        }

        /**
         * 把周销量、可用库存、在途库存三个数组根据键值 [account_id ：sku]合并，不存在的补0
         */
        if (!empty($reportSaleData)) {
            foreach ($reportSaleData as &$data) {
                if (isset($inventoryData[$data['account_id'] . ':' . $data['sku']])) {
                    $data['inventory'] = $inventoryData[$data['account_id'] . ':' . $data['sku']]['inventory'];
                    unset($inventoryData[$data['account_id'] . ':' . $data['sku']]);
                } else {
                    $data['inventory'] = 0;
                }
                if (isset($unsuppressedInventoryData[$data['account_id'] . ':' . $data['sku']])) {
                    $data['unsuppressedInventory'] = $unsuppressedInventoryData[$data['account_id'] . ':' . $data['sku']]['unsuppressedInventory'];
                    unset($unsuppressedInventoryData[$data['account_id'] . ':' . $data['sku']]);
                } else {
                    $data['unsuppressedInventory'] = 0;
                }
                if (isset($oceanShippingData[$data['account_id'] . ':' . $data['sku']])) {
                    $data['ocean'] = $oceanShippingData[$data['account_id'] . ':' . $data['sku']]['ocean'];
                    unset($oceanShippingData[$data['account_id'] . ':' . $data['sku']]);
                } else {
                    $data['ocean'] = 0;
                }
                if (isset($airTransportData[$data['account_id'] . ':' . $data['sku']])) {
                    $data['air'] = $airTransportData[$data['account_id'] . ':' . $data['sku']]['air'];
                    unset($airTransportData[$data['account_id'] . ':' . $data['sku']]);
                } else {
                    $data['air'] = 0;
                }
                if (isset($saleConfirmQuantityData[$data['account_id'] . ':' . $data['sku']])) {
                    $data['homeNum'] = $saleConfirmQuantityData[$data['account_id'] . ':' . $data['sku']]['homeNum'];
                    unset($saleConfirmQuantityData[$data['account_id'] . ':' . $data['sku']]);
                } else {
                    $data['homeNum'] = 0;
                }

                $data['sellerName'] = isset($sellerManName[$data['account_id']]) ? $sellerManName[$data['account_id']] : '';
                $data['saleStatus'] = $saleStatusData[$data['sale_status_id']] ? $saleStatusData[$data['sale_status_id']] : '';

            }
        }

        if (!empty($inventoryData)) {
            foreach ($inventoryData as $key => &$value) {
                $value['daysale'] = 0;
                $value['sellerName'] = isset($sellerManName[$value['account_id']]) ? $sellerManName[$value['account_id']] : '';
                $value['saleStatus'] = $saleStatusData[$value['sale_status_id']] ? $saleStatusData[$value['sale_status_id']] : '';
                if (isset($unsuppressedInventoryData[$value['account_id'] . ':' . $value['sku']])) {
                    $value['unsuppressedInventory'] = $unsuppressedInventoryData[$value['account_id'] . ':' . $value['sku']]['unsuppressedInventory'];
                    unset($unsuppressedInventoryData[$value['account_id'] . ':' . $value['sku']]);
                } else {
                    $value['unsuppressedInventory'] = 0;
                }
                if (isset($oceanShippingData[$value['account_id'] . ':' . $value['sku']])) {
                    $value['ocean'] = $oceanShippingData[$value['account_id'] . ':' . $value['sku']]['ocean'];
                    unset($oceanShippingData[$value['account_id'] . ':' . $value['sku']]);
                } else {
                    $value['ocean'] = 0;
                }
                if (isset($airTransportData[$value['account_id'] . ':' . $value['sku']])) {
                    $value['air'] = $airTransportData[$value['account_id'] . ':' . $value['sku']]['air'];
                    unset($airTransportData[$value['account_id'] . ':' . $value['sku']]);
                } else {
                    $value['air'] = 0;
                }
                if (isset($saleConfirmQuantityData[$value['account_id'] . ':' . $value['sku']])) {
                    $value['homeNum'] = $saleConfirmQuantityData[$value['account_id'] . ':' . $value['sku']]['homeNum'];
                    unset($saleConfirmQuantityData[$value['account_id'] . ':' . $value['sku']]);
                } else {
                    $value['homeNum'] = 0;
                }
                $reportSaleData[] = $value;
            }
        }

        if (!empty($unsuppressedInventoryData)) {
            foreach ($unsuppressedInventoryData as $key => &$value) {
                $value['daysale'] = 0;
                $value['inventory'] = 0;
                $value['sellerName'] = isset($sellerManName[$value['account_id']]) ? $sellerManName[$value['account_id']] : '';
                $value['saleStatus'] = $saleStatusData[$value['sale_status_id']] ? $saleStatusData[$value['sale_status_id']] : '';
                if (isset($oceanShippingData[$value['account_id'] . ':' . $value['sku']])) {
                    $data['ocean'] = $oceanShippingData[$value['account_id'] . ':' . $value['sku']]['ocean'];
                    unset($oceanShippingData[$value['account_id'] . ':' . $value['sku']]);
                } else {
                    $value['ocean'] = 0;
                }
                if (isset($airTransportData[$value['account_id'] . ':' . $value['sku']])) {
                    $value['air'] = $airTransportData[$value['account_id'] . ':' . $value['sku']]['air'];
                    unset($airTransportData[$value['account_id'] . ':' . $value['sku']]);
                } else {
                    $value['air'] = 0;
                }
                if (isset($saleConfirmQuantityData[$value['account_id'] . ':' . $value['sku']])) {
                    $value['homeNum'] = $saleConfirmQuantityData[$value['account_id'] . ':' . $value['sku']]['homeNum'];
                    unset($saleConfirmQuantityData[$value['account_id'] . ':' . $value['sku']]);
                } else {
                    $value['homeNum'] = 0;
                }
                $reportSaleData[] = $value;
            }
        }

        if (!empty($oceanShippingData)) {
            foreach ($oceanShippingData as $key => &$value) {
                $value['daysale'] = 0;
                $value['inventory'] = 0;
                $value['unsuppressedInventory'] = 0;
                $value['sellerName'] = isset($sellerManName[$value['account_id']]) ? $sellerManName[$value['account_id']] : '';
                $value['saleStatus'] = $saleStatusData[$value['sale_status_id']] ? $saleStatusData[$value['sale_status_id']] : '';
                if (isset($airTransportData[$value['account_id'] . ':' . $value['sku']])) {
                    $value['air'] = $airTransportData[$value['account_id'] . ':' . $value['sku']]['qty'];
                    unset($airTransportData[$value['account_id'] . ':' . $value['sku']]);
                } else {
                    $value['air'] = 0;
                }
                if (isset($saleConfirmQuantityData[$value['account_id'] . ':' . $value['sku']])) {
                    $value['homeNum'] = $saleConfirmQuantityData[$value['account_id'] . ':' . $value['sku']]['homeNum'];
                    unset($saleConfirmQuantityData[$value['account_id'] . ':' . $value['sku']]);
                } else {
                    $value['homeNum'] = 0;
                }
                $reportSaleData[] = $value;
            }
        }

        if (!empty($airTransportData)) {
            foreach ($airTransportData as $key => &$value) {
                $value['daysale'] = 0;
                $value['inventory'] = 0;
                $value['unsuppressedInventory'] = 0;
                $value['sellerName'] = isset($sellerManName[$value['account_id']]) ? $sellerManName[$value['account_id']] : '';
                $value['saleStatus'] = $saleStatusData[$value['sale_status_id']] ? $saleStatusData[$value['sale_status_id']] : '';
                $value['ocean']  = 0;
                if (isset($saleConfirmQuantityData[$value['account_id'] . ':' . $value['sku']])) {
                    $value['homeNum'] = $saleConfirmQuantityData[$value['account_id'] . ':' . $value['sku']]['homeNum'];
                    unset($saleConfirmQuantityData[$value['account_id'] . ':' . $value['sku']]);
                } else {
                    $value['homeNum'] = 0;
                }
                $reportSaleData[] = $value;
            }
        }

        if (!empty($saleConfirmQuantityData)) {
            foreach ($saleConfirmQuantityData as $key => &$value) {
                $value['daysale'] = 0;
                $value['inventory'] = 0;
                $value['unsuppressedInventory'] = 0;
                $value['sellerName'] = isset($sellerManName[$value['account_id']]) ? $sellerManName[$value['account_id']] : '';
                $value['saleStatus'] = $saleStatusData[$value['sale_status_id']] ? $saleStatusData[$value['sale_status_id']] : '';
                $value['ocean']  = 0;
                $value['air'] = 0;
                $reportSaleData[] = $value;
            }
        }



        return $reportSaleData;
    }

    /**
     * @param $data
     * @param $excelFileName
     * 描述：字符串下载 Excel
     */
    public function export($data,$excelFileName){
        set_time_limit(0);
        ini_set('memory_limit','1024M');
        $firstLine = array(
            'sellerName'            => '销售',
            'shorthand_code'        => '站点',
            'accountName'           => '店铺帐号',
            'sku'                   => 'SellerSKU',
            'asin'                  => 'ASIN',
            'daysale'               => '日均销量',
            'private_sku'           => '公司SKU',
            'sku_cnname'            => '品名'
            /*'inventory'             => 'FBA库存',
            'unsuppressedInventory' => '国际在途',*/
        );
        /* 获取字段名称 */
        $keys    = array_keys($firstLine);
        $content = "";
        $content .= "<table border='1'><tr>";
        foreach($firstLine as $_pre){
            $content .= "<td>$_pre</td>";
        }
        $content .= "</tr>";
        foreach($data as $_list){
            $content .= "<tr>";
            foreach($keys as $key){
                $content .= "<td style='vnd.ms-excel.numberformat:@'>".$_list[$key]."</td>";
            }
            $content .= "</tr>";
        }
        $content .= "</table>";
        header("Content-type:application/vnd.ms-execl;charset=gb2312");
        header("Content-Disposition:attactment;filename=".$excelFileName.".xls");
        header("Pragma: no-cache");
        header("Expires: 0");
        echo $content;
        exit;
    }

    public function getSkuQuantity($condition) {
        $skuQuantityData = $this->reportSaleModel->getSkuQuantity($condition);
        return $skuQuantityData;
    }

    public function downloadSingleData($downloadType) {
        $serviceName = "report" . ucfirst($downloadType) . "Model";
        $result = $this->$serviceName->getSingleData();

        $this->prepareneedsService->download_function($result['data'], $result['title'], $result['fileName']);

    }
}